﻿#include "BuddyListWidget.h"
#include "BuddyListChild.h"
#include "ContactsWidget.h"
#include "ShowGroupBtn.h"
#include "FriendInfoDlg.h"
#include "ChatWin.h"
#include "global.h"

#include <QResizeEvent>
#include <QAction>
#include <QMenu>
#include <QDebug>
#include <QPropertyAnimation>
#pragma execution_character_set("utf-8")
BuddyListWidget::BuddyListWidget(QWidget *parent)
    : QListWidget(parent),
      m_pCurrentChild(NULL)
{
    this->setObjectName("BuddyListWidget");
    this->setMouseTracking(true);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);     //关闭横向滚动条
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);       //关闭纵向滚动条
    this->setFrameShape(QListWidget::NoFrame);
    //this->setStyleSheet("background-color:transparent");
    this->setAcceptDrops(true);                      // 设置窗口部件可以接收拖入
    //去掉选中项的虚线框
    //this->setFocusPolicy(Qt::NoFocus);
    this->setSelectionMode(QAbstractItemView::SingleSelection);
    //允许排序
    this->setSortingEnabled(true);

    initUi();
    initMenu();
}

BuddyListWidget::~BuddyListWidget()
{
    this->clear();
    for(auto item : m_mapFriendInfoDlg)
    {
        delete item;
    }
}

void BuddyListWidget::initUi()
{
    connect(this,&BuddyListWidget::sigShowFriendInfo,this,&BuddyListWidget::SltShowFriendInfo);
}

void BuddyListWidget::initMenu()
{
    m_pMenu = new QMenu(this);
    QAction *SendMsg = new QAction(tr("发送即时消息"),this);
    QAction *SendEmail = new QAction(tr("发送电子邮件"),this);
    QAction *ViewUserInfo = new QAction(tr("查看资料"),this);
    QAction *editRemark = new QAction(tr("修改备注名"),this);
    QAction *delFriend = new QAction(tr("删除好友"),this);
    QMenu   *menu = new QMenu(tr("移动联系人至"),this);

    m_pMenu->addAction(SendMsg);
    m_pMenu->addAction(SendEmail);
    m_pMenu->addSeparator();
    m_pMenu->addAction(ViewUserInfo);
    m_pMenu->addAction(editRemark);
    m_pMenu->addAction(delFriend);
    m_pMenu->addMenu(menu);

    connect(m_pMenu, &QMenu::triggered, this, &BuddyListWidget::SltMenuClicked);
}

void BuddyListWidget::addChildItem(QQCellChild *child)
{
    BuddyListChild *childWidget = new BuddyListChild;
    connect(childWidget,&BuddyListChild::sigShowFriendInfo,this,&BuddyListWidget::SltShowFriendInfo);
    connect(child,&QQCellChild::sigUnReadMsg,this,&BuddyListWidget::startAnimation);
    connect(child,&QQCellChild::sigClearUnReadMsg,this,&BuddyListWidget::stopAnimation);

    childWidget->setGeometry(0,0,360,80);
    childWidget->setQQCell(child);
    //仅仅为了排序
    QString str = child->m_status == STATUS_ONLINE ? "A":"Z";

    QListWidgetItem * item = new QListWidgetItem(str,this);
    item->setData(Qt::UserRole,child->m_id);
    //item->setData(Qt::InitialSortOrderRole,str);

    //this->addItem(item);
    this->setItemWidget(item, childWidget);
    item->setSizeHint(childWidget->geometry().size());
    //this->sortItems(Qt::AscendingOrder);
}

void BuddyListWidget::removeChildItem(QQCellChild *child)
{
    Q_UNUSED(child);
}

//删除好友，如果打开了个人信息窗口也要删除
bool BuddyListWidget::removeChildItem(int userid)
{
    qDebug() << "BuddyListWidget::removeChildItem";
    if(m_mapFriendInfoDlg.find(m_pCurrentChild->m_id) != m_mapFriendInfoDlg.end())
    {
        FriendInfoDlg* dlg = nullptr;
        dlg = m_mapFriendInfoDlg[m_pCurrentChild->m_id];
        dlg->SltBtnClicked();
    }

    for(int i = 0;i<this->count();i++)
    {
        QListWidgetItem* item = this->item(i);

        if(userid == item->data(Qt::UserRole))
        {
            QListWidgetItem * item= this->takeItem(i);
            delete item;
            return true;
        }
    }
    return false;
}

/**
 * @brief BuddyListWidget::setAutoLayoutSize
 * 每次分组添加新成员都要重新计算分组的高度以及外层widget的高度
 */
void BuddyListWidget::setAutoLayoutSize()
{
    int minheight = 0;
    foreach(BuddyListGroup *group, m_pContactsWidget->getBuddyListGroupVector())
    {
        int height = 0;
        int btnHeight = group->m_pBtnList->height();

        if( !group->m_pListwidget->isHidden())
        {
            for(int i = 0; i<group->m_pListwidget->count();i++)
            {
                height += 80;       //每一个item的行高
            }
            group->m_pListwidget->setMinimumHeight(height);
            group->setMaximumHeight(height + btnHeight);
            minheight += height + btnHeight;
        }else
        {
            group->m_pListwidget->setMinimumHeight(height);
            group->setMaximumHeight(btnHeight);
            minheight += btnHeight;
        }
    }

    m_pContactsWidget->getWidget()->setMinimumHeight(minheight);
}

//对应userid的好友头像闪动
void BuddyListWidget::startAnimation(int userid)
{
    if(m_RecvMsgIds.contains(userid))
        return;
    //分组标题闪烁
    m_pGroup->groupTwinkle();

    for(int i = 0;i<this->count();i++)
    {
        QListWidgetItem* item = this->item(i);

        if(userid == item->data(Qt::UserRole))
        {
            BuddyListChild* w = qobject_cast<BuddyListChild*>(this->itemWidget(item));
            QPushButton* btn= &(w->m_headBtn);
            //此处要指定父对象，如果动画没有stop关闭窗口，可以由QT父子对象管理机制析构该空间
            QPropertyAnimation *pAnimation = new QPropertyAnimation(btn, "pos",btn);
            pAnimation->setDuration(800);
            pAnimation->setLoopCount(-1);
            pAnimation->setKeyValueAt(0, QPoint(btn->geometry().x(), btn->geometry().y()));
            pAnimation->setKeyValueAt(0.2, QPoint(btn->geometry().x()+2, btn->geometry().y()));
            pAnimation->setKeyValueAt(0.6, QPoint(btn->geometry().x()+5, btn->geometry().y()+5));
            pAnimation->setKeyValueAt(0.8, QPoint(btn->geometry().x()+2, btn->geometry().y()));
            pAnimation->setKeyValueAt(1, QPoint(btn->geometry().x(), btn->geometry().y()));
            pAnimation->start(QAbstractAnimation::DeleteWhenStopped);
            m_RecvMsgIds[userid] = pAnimation;
            return;
        }
    }

}

//停止头像闪动
void BuddyListWidget::stopAnimation(int userid)
{
    if(m_RecvMsgIds.contains(userid))
    {
        QPropertyAnimation* animation = m_RecvMsgIds[userid];
        animation->stop();
        m_RecvMsgIds.remove(userid);
        if(m_RecvMsgIds.size() == 0)
        {
            m_pGroup->SltStopTwinkle();
        }
    }
}

QListWidgetItem *BuddyListWidget::getListwidgetItemByUserid(int userid)
{
    for(int i = 0;i<this->count();i++)
    {
        QListWidgetItem* item = this->item(i);

        if(userid == item->data(Qt::UserRole))
        {
            return item;
        }
    }
    return NULL;
}

void BuddyListWidget::resizeEvent(QResizeEvent *e)
{
    QListWidget::resizeEvent(e);
}

void BuddyListWidget::mousePressEvent(QMouseEvent *evt)
{
    qDebug() << "BuddyListWidget::mousePressEvent";
    QListWidget::mousePressEvent(evt);
    //获取当前的好友信息
    QListWidgetItem* curItem = itemAt(evt->pos());
    BuddyListChild* widget = qobject_cast<BuddyListChild*>(itemWidget(curItem));
    m_pCurrentChild = widget->getQQCell();

    if(evt->button()==Qt::RightButton)
    {
        m_pMenu->exec(QCursor::pos());
    }
    evt->ignore();
}

void BuddyListWidget::mouseDoubleClickEvent(QMouseEvent *evt)
{
    qDebug() << "BuddyListWidget::mouseDoubleClickEvent";
    if( evt->buttons() == Qt::LeftButton)
    {
        this->stopAnimation(m_pCurrentChild->m_id);
        Q_EMIT m_pContactsWidget->sigOpenChatWin(m_pCurrentChild);
    }
}

void BuddyListWidget::mouseMoveEvent(QMouseEvent *evt)
{
    Q_UNUSED(evt);
    //qDebug() << "BuddyListWidget::mouseMoveEvent";
}

void BuddyListWidget::focusOutEvent(QFocusEvent *event)
{
    this->selectionModel()->clearSelection();
    QListWidget::focusOutEvent(event);
}

void BuddyListWidget::focusInEvent(QFocusEvent *event)
{
    QListWidget::focusInEvent(event);
}

void BuddyListWidget::SltMenuClicked(QAction *action)
{
    if ("发送即时消息" == action->text())
    {
        this->stopAnimation(m_pCurrentChild->m_id);
        Q_EMIT m_pContactsWidget->sigOpenChatWin(m_pCurrentChild);
    }else if("发送电子邮件" == action->text())
    {

    }else if("查看资料" == action->text())
    {
        Q_EMIT sigShowFriendInfo(m_pCurrentChild);
    }else if("修改备注名" == action->text())
    {

    }else if("删除好友" == action->text())
    {
        Q_EMIT m_pContactsWidget->sigDelFriend(m_pCurrentChild->m_id);
    }else if("移动联系人至" == action->text())
    {

    }
}

void BuddyListWidget::SltFriendInfoDlgClosed(int id)
{
    qDebug() << "BuddyListWidget::SltFriendInfoDlgClosed(int id)1";
    m_mapFriendInfoDlg.remove(id);
}

void BuddyListWidget::SltShowFriendInfo(QQCellChild *child)
{
    if(child!=NULL)
    {
        FriendInfoDlg* dlg = nullptr;
        if(m_mapFriendInfoDlg.find(child->m_id) == m_mapFriendInfoDlg.end())
        {
            dlg = new FriendInfoDlg;
            connect(dlg,&FriendInfoDlg::sigFriendInfoDlgClosed,this,&BuddyListWidget::SltFriendInfoDlgClosed);
            dlg->m_id = child->m_id;
            m_mapFriendInfoDlg[child->m_id] = dlg;
        }else
        {
            dlg = m_mapFriendInfoDlg[child->m_id];
        }

        dlg->m_editAccount.setText(QString("%1-%2").arg(child->m_childInfo.username).arg(child->m_childInfo.userid));
        dlg->m_editName.setText(child->m_childInfo.nickname);
        dlg->m_editSign.setText(child->m_childInfo.signature);
        if(child->m_childInfo.gender == 0)
        {
            dlg->m_editSex.setText("男");
        }else
        {
            dlg->m_editSex.setText("女");
        }

        QString str = child->m_childInfo.birthday;
        str.insert(4,'/');
        str.insert(7,'/');
        dlg->m_editBirthday.setText(str);

        dlg->m_editSite.setText(child->m_childInfo.address);
        dlg->m_editTel.setText(child->m_childInfo.phonenumber);
        dlg->m_editEmail.setText(child->m_childInfo.mail);
        dlg->show();
    }
}
